﻿using RestAPI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AxZWANPHONELib;
using TopVisionVideoStream.TopVisionCenter;

namespace TopVisionVideoStream.Mananger
{
    public class MessageManager : IDisposable
    {
        public event MessageReceiveEventHandler MessageReceiveEvent;

        public event UnRegistEventHandler UnRegistEvent;

        public UseBase64Type UseBase64 = UseBase64Type.Header;

        public MessageManager()
        {
            OcxApi.MessageInfoEvent += OcxApi_MessageInfoEvent;
        }

        private void OcxApi_MessageInfoEvent(object sender, _DZwanPhoneEvents_MessageInfoEvent e)
        {
            string sed = e.strSender;
            if (sed.StartsWith("sip"))
            {
                try
                {
                    sed = sed.Replace("sip:", "");
                    if (sed.Contains("@"))
                        sed = sed.Substring(0, sed.IndexOf('@'));
                }
                catch (Exception ex)
                {
                    Console.WriteLine("ERR OcxApi_MessageInfoEvent_e.strSender " + ex.Message);
                }
            }

            MessageReceiveEvent?.Invoke(e.lType, e.strInfo, sed);
        }


        #region Send Message

        DateTime t1 = new DateTime(1970, 1, 1);

        int iType = 1;
        double iReport = 0;
        string pDeliverTime = "1000";
        // string pReceiverURI = "";
        string pLocalMsgID => ((DateTime.Now - t1).TotalMilliseconds).ToString();
        string pTMSubject = "";
        double iFileSeekSize = 0;
        string tmpMsg = "";

        public bool SendMessage(string receiver, string msg)
        {
            Console.WriteLine("msg id:" + receiver + " " + msg);
            return OcxApi.SendMessage(iType, iReport, msg, pDeliverTime, receiver, pLocalMsgID, pTMSubject, iFileSeekSize);
        }

        #region Message Model


        #region Message Command

        public string FlashCmd = "闪光灯";
        public string FlashContent = "闪光灯";
        public string FlashMsg => MessageFormat(FlashCmd + "," + Configuration.Account + "," + FlashContent);

        public string FocusCmd = "点对焦";
        public string FocusContentFmt = "{0},{1},{2},{3}";
        public string FocusContent = "";
        public string FocusMsg => MessageFormat(FocusCmd + "," + Configuration.Account + "," + FocusContent);

        public string ZoomCmd = "焦距";
        public string ZoomContent = "";
        //public string ZoomMsg => MessageFormat(ZoomCmd + "," + Configuration.Account + "," + ZoomContent);
        public string ZoomMsg => MessageFormat(ZoomCmd + "," + ZoomContent);

        public string MarkCmd = "标记";
        public string MarkContentFmt = "{0},{1},{2},{3},{4},{5},{6},{7},{8}";
        public string MarkContent = "";
        public string MarkMsg => MessageFormat(MarkCmd + "," + Configuration.Account + "," + MarkContent);

        public string MarkClearCmd = "清除照片标示";
        public string MarkClearContent = "清除照片标示";
        public string MarkClearMsg => MessageFormat(MarkClearCmd + "," + Configuration.Account + "," + MarkClearContent);

        public string MarkRevokeContent = "清除照片标示LAST";
        public string MarkRevokeMsg => MessageFormat(MarkClearCmd + "," + Configuration.Account + "," + MarkRevokeContent);

        public string PhotoCmd = "拍照";
        public string PhotoContent = "拍照";
        public string PhotoMsg => MessageFormat(PhotoCmd + "," + Configuration.Account + "," + PhotoContent);

        public string PhotoQuitCmd = "结束MatrixImageView";
        public string PhotoQuitContent = "结束MatrixImageView";
        public string PhotoQuitMsg => MessageFormat(PhotoQuitCmd + "," + Configuration.Account + "," + PhotoQuitContent);

        public string TextCmd = "文字";
        public string TextContent = "";
        public string TextMsg => MessageFormat(TextCmd + "," + Configuration.Account + "," + TextContent);

        public string TextClearCmd = "文字消失";
        public string TextClearContent = "文字消失";
        public string TextClearMsg => MessageFormat(TextClearCmd + "," + Configuration.Account + "," + TextClearContent);

        public string VoiceOnlyCmd = "冻结";
        public string VoiceOnlyContent = "冻结";
        public string VoiceOnlyMsg => MessageFormat(VoiceOnlyCmd + "," + Configuration.Account + "," + VoiceOnlyContent);

        public string CamerControlCmd = "相机参数调节";
        public string BrightnessContentFmt = "brightness,{0}";
        public string BrightnessContent = "";
        public string ContrastContentFmt = "contrast,{0}";
        public string ContrastContent = "";
        //public string BrightnessMsg => MessageFormat(CamerControlCmd + "," + Configuration.Account + "," + BrightnessContent);
        //public string ContrastMsg => MessageFormat(CamerControlCmd + "," + Configuration.Account + "," + ContrastContent);
        public string BrightnessMsg => MessageFormat(CamerControlCmd + "," + BrightnessContent);
        public string ContrastMsg => MessageFormat(CamerControlCmd + "," + ContrastContent);

        public string ResolutionCmd = "设置分辨率";
        public string ResolutionContent = "";
        //public string ResolutionMsg => MessageFormat(ResolutionCmd + "," + Configuration.Account + "," + ResolutionContent);
        public string ResolutionMsg => MessageFormat(ResolutionCmd + "," + ResolutionContent);

        public string FileCmd = "文件";
        public string FileContent = "";
        public string FileMsg => MessageFormat(FileCmd + "," + Configuration.Account + "," + FileContent);

        public string ScreenShareCmd = "屏幕共享";
        public string ScreenShareContent = "";
        public string ScreenShareMsg => MessageFormat(ScreenShareCmd + "," + Configuration.Account + "," + ScreenShareContent);

        public string BitRateCmd = "设置码率";
        public string BitRateCmdContent = "";
        public string BitRateCmdMsg => MessageFormat(BitRateCmd + "," + BitRateCmdContent);

        #endregion



        #endregion


        #endregion


        #region Send Method
        /// <summary>
        /// 闪光灯消息
        /// </summary>
        /// <param name="receiver"></param>
        /// <returns></returns>
        public bool SendFlashMessage(string receiver)
        {
            return SendMessage(receiver, FlashMsg);
        }

        public void TVCSendFlashMessage(ConfCallManager confManager)
        {
            TVCSendMessage(FlashMsg, confManager);
        }

        /// <summary>
        /// 对焦消息
        /// </summary>
        /// <param name="receiver">目标</param>
        /// <param name="width">画面宽度</param>
        /// <param name="height">画面调试</param>
        /// <param name="x">对焦坐标X</param>
        /// <param name="y">对焦坐标Y</param>
        /// <returns></returns>
        public bool SendFocusMessage(string receiver, int width, int height, int x, int y)
        {
            FocusContent = string.Format(FocusContentFmt, width, height, x, y);

            return SendMessage(receiver, FocusMsg);
        }

        public void TVCSendFocusMessage(int width, int height, int x, int y, ConfCallManager confManager)
        {
            FocusContent = string.Format(FocusContentFmt, width, height, x, y);

            TVCSendMessage(FocusMsg, confManager);
        }

        /// <summary>
        /// 焦距消息
        /// </summary>
        /// <param name="receiver">目标</param>
        /// <param name="z">放大倍数[0 - 6]</param>
        /// <returns></returns>
        public bool SendZoomMessage(string receiver, double z)
        {
            z = Math.Abs(z);
            z = z > 60 ? 60 : z;
            ZoomContent = z.ToString();
            return SendMessage(receiver, ZoomMsg);
        }

        public void TVCSendZoomMessage(double z, ConfCallManager confManager)
        {
            z = Math.Abs(z);
            z = z > 6 ? 6 : z;
            ZoomContent = z.ToString();

            TVCSendMessage(ZoomMsg, confManager);
        }

        /// <summary>
        /// 标记消息
        /// </summary>
        /// <param name="receiver">目标</param>
        /// <param name="width">画面宽度</param>
        /// <param name="height">画面高度</param>
        /// <param name="sX">标记起点X</param>
        /// <param name="sY">标记起点Y</param>
        /// <param name="eX">标记终点X</param>
        /// <param name="eY">标记终点Y</param>
        /// <param name="pT">标记类型
        /// 1 = 画直线    3 = 画空心矩形    5 = 空心圆    10 = 箭头
        /// </param>
        /// <param name="color">标记颜色
        /// #ff7200    #9943e3    #24def4    #07df8b    #288fe7    #ffe404     #ef3030     #000000
        /// 橙色       紫色       青色       绿色       蓝色       黄色        红色        黑色
        /// </param>
        /// <param name="pWidth">标记线宽
        /// 1,2,4,6
        /// </param>
        public bool SendMarkMessage(string receiver, int width, int height, int sX, int sY, int eX, int eY, int pT, string color, int pWidth, ConfCallManager confManager = null)
        {
            MarkContent = string.Format(MarkContentFmt, width, height, sX, sY, eX, eY, pT, color, pWidth);
            if (confManager != null && confManager.ConfInfo != null)
            {
                WebVideoConfMsg wvcm = new WebVideoConfMsg(Configuration.CompanyID, confManager.ConfInfo.confid, MarkMsg);
                var ret = wvcm.Call();
                return ret == WebRequestError.成功_200;
            }
            else
            {
                return SendMessage(receiver, MarkMsg);
            }
        }

        public void TVCSendMarkMessage(int width, int height, int sX, int sY, int eX, int eY, int pT, string color, int pWidth, ConfCallManager confManager)
        {
            MarkContent = string.Format(MarkContentFmt, width, height, sX, sY, eX, eY, pT, color, pWidth);

            TVCSendMessage(MarkMsg, confManager);
        }

        /// <summary>
        /// 消除标记消息
        /// </summary>
        /// <param name="receiver">目标</param>
        /// <returns></returns>
        public bool SendMarkClearMessage(string receiver, ConfCallManager confManager = null)
        {
            //MarkContent = MarkContent;
            if (confManager != null && confManager.ConfInfo != null)
            {
                WebVideoConfMsg wvcm = new WebVideoConfMsg(Configuration.CompanyID, confManager.ConfInfo.confid, MarkClearMsg);
                var ret = wvcm.Call();
                return ret == WebRequestError.成功_200;
            }
            else
            {
                return SendMessage(receiver, MarkClearMsg);
            }
        }

        public void TVCSendMarkClearMessage(ConfCallManager confManager)
        {
            TVCSendMessage(MarkClearMsg, confManager);
        }

        public bool SendMarkRevoke(string receiver, ConfCallManager confManager = null)
        {
            if (confManager != null && confManager.ConfInfo != null)
            {
                WebVideoConfMsg wvcm = new WebVideoConfMsg(Configuration.CompanyID, confManager.ConfInfo.confid, MarkRevokeMsg);
                var ret = wvcm.Call();
                return ret == WebRequestError.成功_200;
            }
            else
            {
                return SendMessage(receiver, MarkRevokeMsg);
            }
        }

        public void TVCSendMarkRevoke(ConfCallManager confManager)
        {
            TVCSendMessage(MarkRevokeMsg, confManager);
        }

        /// <summary>
        /// 拍照消息
        /// </summary>
        /// <param name="receiver">目标</param>
        /// <returns></returns>
        public bool SendPhotoMessage(string receiver)
        {
            //PhotoContent =  PhotoContent;
            return SendMessage(receiver, PhotoMsg);
        }

        public void TVCSendPhotoMessage(ConfCallManager confManager)
        {
            TVCSendMessage(PhotoMsg, confManager);
        }

        /// <summary>
        /// 退出拍照消息
        /// </summary>
        /// <param name="receiver"></param>
        /// <returns></returns>
        public bool SendPhotoQuitessage(string receiver)
        {
            //PhotoQuitContent =  PhotoQuitContent;
            return SendMessage(receiver, PhotoQuitMsg);
        }

        public void TVCSendPhotoQuitessage(ConfCallManager confManager)
        {
            TVCSendMessage(PhotoQuitMsg, confManager);
        }

        /// <summary>
        /// 文本消息
        /// </summary>
        /// <param name="receiver">目标</param>
        /// <param name="txt">文本内容</param>
        /// <returns></returns>
        public bool SendTextMessage(string receiver, string txt, ConfCallManager confManager = null)
        {
            TextContent = txt;

            if (confManager != null && confManager.ConfInfo != null)
            {
                WebVideoConfMsg wvcm = new WebVideoConfMsg(Configuration.CompanyID, confManager.ConfInfo.confid, TextMsg);
                var ret = wvcm.Call();
                return ret == WebRequestError.成功_200;
            }
            else
            {
                return SendMessage(receiver, TextMsg);
            }
        }

        public void TVCSendTextMessage(string txt, ConfCallManager confManager)
        {
            TextContent = txt;

            TVCSendMessage(TextMsg, confManager);
        }

        /// <summary>
        /// 文本消失消息
        /// </summary>
        /// <param name="receiver">目标</param>
        /// <returns></returns>
        public bool SendTextClearMessage(string receiver, ConfCallManager confManager = null)
        {
            //TextClearContent = TextClearContent;
            if (confManager != null && confManager.ConfInfo != null)
            {
                WebVideoConfMsg wvcm = new WebVideoConfMsg(Configuration.CompanyID, confManager.ConfInfo.confid, TextClearMsg);
                var ret = wvcm.Call();
                return ret == WebRequestError.成功_200;
            }
            else
            {
                return SendMessage(receiver, TextClearMsg);
            }
        }

        public void TVCSendTextClearMessage(ConfCallManager confManager)
        {
            TVCSendMessage(TextClearMsg, confManager);
        }

        /// <summary>
        /// 语音切换消息
        /// </summary>
        /// <param name="receiver">目标</param>
        /// <returns></returns>
        public bool SendVoiceOnlyMessage(string receiver)
        {
            //VoiceOnlyContent =  VoiceOnlyContent;
            return SendMessage(receiver, VoiceOnlyMsg);
        }

        public void TVCSendVoiceOnlyMessage(ConfCallManager confManager)
        {
            TVCSendMessage(VoiceOnlyMsg, confManager);
        }

        /// <summary>
        /// 设置亮度消息
        /// </summary>
        /// <param name="receiver">目标</param>
        /// <param name="add">增量</param>
        /// <returns></returns>
        public bool SendBrightnessMessage(string receiver, int add)
        {
            BrightnessContent = string.Format(BrightnessContentFmt, add);

            return SendMessage(receiver, BrightnessMsg);
        }

        public void TVCSendBrightnessMessage(int add, ConfCallManager confManager)
        {
            BrightnessContent = string.Format(BrightnessContentFmt, add);

            TVCSendMessage(BrightnessMsg, confManager);
        }

        /// <summary>
        /// 设置对比度消息
        /// </summary>
        /// <param name="receiver">目标</param>
        /// <param name="add">增量</param>
        /// <returns></returns>
        public bool SendContrastMessage(string receiver, int add)
        {
            ContrastContent = string.Format(ContrastContentFmt, add);
            return SendMessage(receiver, ContrastMsg);
        }

        public void TVCSendContrastMessage(int add, ConfCallManager confManager)
        {
            ContrastContent = string.Format(ContrastContentFmt, add);

            TVCSendMessage(ContrastMsg, confManager);
        }

        /// <summary>
        /// 设置分辨率消息
        /// </summary>
        /// <param name="receiver">目标</param>
        /// <param name="resolution">分辨率// switch_cif | switch_vga | switch_720p | switch_1080p</param>
        /// <returns></returns>
        public bool SendResolutionMessage(string receiver, string resolution)
        {
            ResolutionContent = resolution;
            return SendMessage(receiver, ResolutionMsg);
        }

        public void TVCSendResolutionMessage(string resolution, ConfCallManager confManager)
        {
            ResolutionContent = resolution;

            TVCSendMessage(ResolutionMsg, confManager);
        }

        /// <summary>
        /// 发送文件地址
        /// </summary>
        /// <param name="receiver"></param>
        /// <param name="file"></param>
        /// <param name="confManager"></param>
        /// <returns></returns>
        public bool SendFileMessage(string receiver, string file, ConfCallManager confManager = null)
        {
            FileContent = file;
            if (confManager != null && confManager.ConfInfo != null)
            {
                WebVideoConfMsg wvcm = new WebVideoConfMsg(Configuration.CompanyID, confManager.ConfInfo.confid, FileMsg);
                var ret = wvcm.Call();
                return ret == WebRequestError.成功_200;
            }
            else
            {
                return SendMessage(receiver, FileMsg);
            }

        }

        /// <summary>
        /// 设置码率消息
        /// </summary>
        /// <param name="receiver">目标</param>
        /// <param name="resolution">码率</param>
        /// <returns></returns>
        public bool SendBitRateMessage(string receiver, string resolution)
        {
            BitRateCmdContent = resolution;
            return SendMessage(receiver, BitRateCmdMsg);
        }

        public void TVCSendBitRateMessage(string resolution, ConfCallManager confManager)
        {
            BitRateCmdContent = resolution;

            TVCSendMessage(BitRateCmdMsg, confManager);
        }

        public void TVCSendFileMessage(string file, ConfCallManager confManager)
        {
            FileContent = file;

            TVCSendMessage(FileMsg, confManager);
        }

        public bool SendScreenShareMessage(string receiver, bool ON, ConfCallManager confManager = null)
        {
            ScreenShareContent = ON ? "on" : "off";

            if (confManager == null || confManager.ConfInfo == null)
            {
                return SendMessage(receiver, ScreenShareMsg);
            }
            else
            {
                WebVideoConfMsg wvcm = new WebVideoConfMsg(Configuration.CompanyID, confManager.ConfInfo.confid, ScreenShareMsg);

                var ret = wvcm.Call();

                return ret == WebRequestError.成功_200;
            }
        }

        public void TVCSendScreenShareMessage(bool ON, ConfCallManager confManager)
        {
            ScreenShareContent = ON ? "on" : "off";

            TVCSendMessage(ScreenShareMsg, confManager);
        }


        #endregion

        public async void TVCSendMessage(string content, ConfCallManager confManager)
        {
            if (confManager == null) return;

            TVCConferenceConfmsgModel model = new TVCConferenceConfmsgModel();

            model.companyid = Configuration.CompanyID;

            model.confid = confManager.ConfInfo.confid;

            model.content = content.Replace("\"", "'");

            TVCenter center = new TVCenter();

            var result = await center.ConferenceConfmsg(model);

            //Console.WriteLine(string.Format("\r\nTVCSenderMessage:{0}\r\n{1}", result.success, result.msg));
        }


        public string MessageFormat(string str)
        {
            int pos = str.IndexOf(',');
            string header = str.Substring(0, pos);
            string content = str.Substring(pos + 1);
            string msg = "";
            switch (UseBase64)
            {
                case UseBase64Type.None:
                    msg = header + "," + content;
                    break;
                case UseBase64Type.Header:
                    msg = header.ToBase64() + "," + content;
                    break;
                case UseBase64Type.Content:
                    msg = header + "," + content.ToBase64();
                    break;
                case UseBase64Type.Both:
                    msg = (header + "," + content).ToBase64();
                    break;
                default:
                    break;
            }
            return msg;
        }


        //public class MeetingMemberState
        //{
        //    /// <summary>
        //    /// 
        //    /// </summary>
        //    public string number { get; set; }
        //    /// <summary>
        //    /// 
        //    /// </summary>
        //    public int event { get; set; }
        //}

        //public class Root
        //{
        //    /// <summary>
        //    /// 
        //    /// </summary>
        //    public string confid { get; set; }
        //    /// <summary>
        //    /// 
        //    /// </summary>
        //    public Content content { get; set; }
        //}



        public void Dispose()
        {
            OcxApi.MessageInfoEvent -= OcxApi_MessageInfoEvent;
        }


        public static string CmdTypeString(MessageCmdType cmdType)
        {
            switch (cmdType)
            {
                case MessageCmdType.Text:
                    return "文字";
                case MessageCmdType.Flash:
                    return "闪光灯";
                case MessageCmdType.Focus:
                    return "点对焦";
                case MessageCmdType.Zoom:
                    return "焦距";
                case MessageCmdType.Mark:
                    return "标记";
                case MessageCmdType.Photo:
                    return "拍照";
                case MessageCmdType.MarkClear:
                    return "清除照片标示";
                case MessageCmdType.TextClear:
                    return "文字消失";
                case MessageCmdType.Frozen:
                    return "冻结";
                case MessageCmdType.PhotoQuit:
                    return "结束MatrixImageView";
                case MessageCmdType.CameraControl:
                    return "相机参数调节";
                case MessageCmdType.Resolution:
                    return "设置分辨率";
                case MessageCmdType.MarkClearLast:
                    return "";
                case MessageCmdType.File:
                    return "文件";
                case MessageCmdType.Sensor:
                    return "传感器";
                case MessageCmdType.Bitrate:
                    return "设置码率";
                case MessageCmdType.Distinguish:
                    return "识别";
                case MessageCmdType.ScreenModeChanged:
                    return "切换分屏模式";
                case MessageCmdType.MeetingMode:
                    return "模式";
                default:
                    return "";
            }
        }


        public enum UseBase64Type
        {
            None,
            Header,
            Content,
            Both,
        }

        public enum MessageCmdType
        {
            Text = 0,
            Flash,
            Focus,
            Zoom,
            Mark,
            Photo,
            MarkClear,
            TextClear,
            Frozen,
            PhotoQuit,
            CameraControl,
            Resolution,
            MarkClearLast,
            File,
            Sensor,
            Bitrate,
            Distinguish,
            ScreenModeChanged,
            MeetingMode,
        }
    }
}

